package org.mj.im.server.netty.processor.impl;

import io.netty.channel.ChannelHandlerContext;
import org.mj.im.common.MessageSenderService;
import org.mj.im.common.enums.IMCmdType;
import org.mj.im.common.enums.IMSendCode;
import org.mj.im.common.model.IMReceiveInfo;
import org.mj.im.common.model.IMSendInfo;
import org.mj.im.common.model.IMUserInfo;
import org.mj.im.server.cache.UserChannelContextCache;

import org.mj.im.server.netty.processor.MessageProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class GroupMessageProcessor extends BaseMessageProcessor implements MessageProcessor<IMReceiveInfo> {
    private final Logger logger = LoggerFactory.getLogger(GroupMessageProcessor.class);
    public GroupMessageProcessor(MessageSenderService messageSenderService) {
        super(messageSenderService);
    }

    @Override
    public void process(IMReceiveInfo receiveInfo) {
        IMUserInfo sender = receiveInfo.getSender();
        List<IMUserInfo> receivers = receiveInfo.getReceivers();
        logger.info("GroupMessageProcessor process: sender:{},receivers:{},message:{}", sender,receivers,receiveInfo.getData());
        receivers.forEach(receiver->{
            try{
                ChannelHandlerContext channelHandlerContext = UserChannelContextCache.get(receiver.getUserId(),receiver.getTerminal());
                if (channelHandlerContext != null){
                    IMSendInfo<?> imSendInfo = new IMSendInfo<>(IMCmdType.GROUP_MESSAGE.getCode(), receiveInfo.getData());
                    channelHandlerContext.writeAndFlush(imSendInfo);
                    sendGroupMessageResult(receiveInfo,receiver, IMSendCode.SUCCESS);
                }else {
                    sendGroupMessageResult(receiveInfo,receiver,IMSendCode.NOT_FIND_CHANNEL);
                    logger.error("GroupMessageProcessor not find receiver, sender:{},receivers:{},message:{}", sender,receivers,receiveInfo.getData());
                }
            }catch (Exception e){
                sendGroupMessageResult(receiveInfo,receiver,IMSendCode.UNKNOWN_ERROR);
                logger.error("GroupMessageProcessor process error, sender:{},receiver:{}, message:{} ",sender,receiver,receiveInfo.getData(), e);

            }
        });
    }
}